/*
 * @LastEditTime: 2023-02-28 11:30:54
 */
import { Comment } from "../Models/Comment.schema";
import { createCommentDTO, updateCommentDTO } from "../DTO/Comment.dto";
import { isExistsforId, isExistsforTitle } from "../hook";

export class CommentController {
  constructor(private readonly commentModel: typeof Comment) { }
  /**
 * 创建评论
 * @param dto 数据传输对象
 * @returns 返回创建对象
 */
  async createItem(dto: createCommentDTO) {
    try {
      return {
        code: 200,
        message: "创建成功",
        data: await this.commentModel.create(dto),
      };
    } catch (error) {
      return await error;
    }
  }

  /**
 * 以ID为查找依据删除评论
 * @param id 要删除元素的唯一ID
 * @returns
  */
  async removeById(userName: string) {
    try {
      if (!await isExistsforId(userName, this.commentModel)) {
        return {
          code: 400,
          message: '不存在查询的ID',
        }
      } else {
        return {
          code: 200,
          message: "删除成功",
          data: await this.commentModel.deleteOne({ _id: userName }),
        };
      }
    } catch (error) {
      return await error;
    }
  }
  /**
   * 按ID更新评论
   * @param id 要更新的ID
   * @param dto  要更新的内容
   * @returns 更新对象
   */
  async updateById(id: string, dto: updateCommentDTO) {
    try {
      if (!await isExistsforId(id, this.commentModel)) {
        return {
          code: 400,
          message: '不存在查询的ID',
        }
      } else {
        return {
          code: 200,
          message: "更新成功",
          data: await this.commentModel.updateOne({ _id: id }, dto),
        };
      }
    } catch (error) {
      return await error;
    }
  }

  /**
  * 按用户名称查找评论
  * @param title 要查找的评论名称
  * @returns 查询对象
  */
  async findByUsername(name: string) {
    try {
      const res = await this.commentModel.find({ username: name })
      return {
        code: 200,
        message: "查找成功",
        data: res
      }

    } catch (error) {
      return await error;
    }
  }

  /**
   * 查找评论
   * @param id 要查找的评论的歌曲id
   * @returns 查询对象
  sws */
  async findById(musicId: string) {
    try {
      if (!await isExistsforId(musicId, this.commentModel)) {
        const res = await this.commentModel.find({ musicId: musicId }).sort({ createdAt: -1 })
        return {
          code: 200,
          message: "查找成功",
          data: res
        }

      } else {
        return {
          code: 200,
          message: "查询成功",
          data: await this.commentModel.find({ musicId: musicId }),
        };
      }
    } catch (error) {
      return await error;
    }
  }
}